//
//  StudentViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2018/1/1.
//  Copyright © 2018年 YRX. All rights reserved.
//

#import "StudentViewController.h"
#import "BrowseResultViewController.h"
#import "IAStudent.h"
#import "IAStudentTableCell.h"

static NSString * const IAStudentCellID = @"IAStudentCellID";

@interface StudentViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray <IAStudent *> *students;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation StudentViewController

- (instancetype)initWithStudents:(NSArray <IAStudent *> *)students {
    self = [super init];
    if (self) {
        _students = students;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"学生列表";
    if (!self.selectedHandler) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    }
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.bounds;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.rowHeight = 111.0f;
    [self.view addSubview:_tableView];
}

- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - tableview

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.students.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IAStudentTableCell *cell = [tableView dequeueReusableCellWithIdentifier:IAStudentCellID];
    if (!cell) {
        cell = [[IAStudentTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IAStudentCellID];
    }
    IAStudent *stu = self.students[indexPath.row];
    cell.student = stu;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    IAStudent *stu = self.students[indexPath.row];
    if (self.selectedHandler) { // 从选择学生的页面过来
        self.selectedHandler(stu);
        self.selectedHandler = nil;
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        BrowseResultViewController *browseController = [[BrowseResultViewController alloc] initWithStudent:stu];
        [self.navigationController pushViewController:browseController animated:YES];
    }
}

@end
